function encryption(key, str) {
    var matrix = key.split('\n');
    var res = ''
    for (pair of str.match(/.{1,2}/g)) {
        if (pair.length === 1) res += pair;
        else {
            var [a, b] = [...pair];
            var row_a = matrix.findIndex(v => v.includes(a));
            var row_b = matrix.findIndex(v => v.includes(b));
            //same letter or miss one letter
            if (a === b || row_a === -1 || row_b === -1) {
                res += pair;
            } else {
                var col_a = matrix[row_a].indexOf(a);
                var col_b = matrix[row_b].indexOf(b);
                console.log(row_a, row_b, col_a, col_b)
                //same row or same column
                if (row_a === row_b || col_a === col_b) res += b + a;
                else {
                    res += matrix[row_a][col_b] + matrix[row_b][col_a];
                }
            }
        }
    }
    return res;
}
